package com.ekingstar.framework.util;

import java.net.InetAddress;

/**
 * @author guoquan
 * 
 */
public class NetTools {

	public static String getLocalHostIP() {
		String ip;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress();
		} catch (Exception ex) {
			ip = "";
		}
		return ip;
	}

	public static String getLocalHostName() {
		String hostName;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			hostName = addr.getHostName();
		} catch (Exception ex) {
			hostName = "";
		}
		return hostName;
	}

	public static String[] getAllLocalHostIP() {
		String[] ret = null;
		try {
			String hostName = getLocalHostName();
			if (hostName.length() > 0) {
				InetAddress[] addrs = InetAddress.getAllByName(hostName);
				if (addrs.length > 0) {
					ret = new String[addrs.length];
					for (int i = 0; i < addrs.length; i++) {
						ret[i] = addrs[i].getHostAddress();
					}
				}
			}

		} catch (Exception ex) {
			ret = null;
		}
		return ret;
	}

	public static String getAllLocalHostIPStr() {
		StringBuffer sb = new StringBuffer("");
		try {
			String hostName = getLocalHostName();
			if (hostName.length() > 0) {
				InetAddress[] addrs = InetAddress.getAllByName(hostName);
				if (addrs.length > 0) {
					for (int i = 0; i < addrs.length; i++) {
						sb = sb.append(addrs[i].getHostAddress()+";");
					}
				}
			}

		} catch (Exception ex) {
			sb = null;
		}
		return sb.toString();
	}
	
	public static String[] getAllHostIPByName(String hostName) {
		String[] ret = null;
		try {
			if (hostName.length() > 0) {
				InetAddress[] addrs = InetAddress.getAllByName(hostName);
				if (addrs.length > 0) {
					ret = new String[addrs.length];
					for (int i = 0; i < addrs.length; i++) {
						ret[i] = addrs[i].getHostAddress();
					}
				}
			}

		} catch (Exception ex) {
			ret = null;
		}
		return ret;
	}
	public static void main(String[] args) {
		// System.out.println(getLocalHostIP());
		System.out.println("主机名：" + getLocalHostName());
		String[] localIP = getAllLocalHostIP();
		
		System.out.println(getAllLocalHostIPStr());
		for (int i = 0; i < localIP.length; i++) {
			System.out.println(localIP[i]);
		}
		System.out.println("--------"+getLocalHostIP());
		String[] ips =  getAllHostIPByName("guoquan");
		for (int i = 0; i < ips.length; i++) {
			System.out.println("-----"+ips[i]);
		}
	}
}
